<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :forceRender="true"
    v-bind:prefixNo="prefixNo"
    switchHelp
    switchFullscreen
    @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp"
    :id="prefixNo"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{$t('inPrint.cancel')}}</a-button>
      <!-- <a-button v-if="isCanCheck" @click="handleOkAndCheck">保存并审核</a-button> -->
      <a-button :disabled="confirmLoading" type="primary" @click="handleCXTJOk(2)">{{$t('commodityManagement.preservation')}}</a-button>
    </template>
    <div style="position:absolute;bottom:53px;right:0;z-index:11" v-if="showRecover && !model.id">
      <span>{{ $t('popup.recoveryPrompt') }}</span>
      <a-button type="link" @click="recover" :disabled="submitBtnDisabled">{{$t('popup.recover')}}</a-button>
      <a-button type="link" @click="lose" :disabled="submitBtnDisabled">{{$t('popup.lose')}}</a-button>
    </div>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
            <a-row class="form-row" :gutter="24">
              <a-col :lg="6" :md="12" :sm="24">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('otherJS.promotionOrderName')" data-step="2" :data-title="$t('otherJS.promotionOrderName')"
                  :data-intro="$t('otherJS.promotionOrderName')">
                  <a-input :placeholder="$t('otherJS.pleaseEnterNamePromotionSlip')" v-decorator="[ 'promotionName',validatorRules.promotionName ]" />
                </a-form-item>
              </a-col> 
              
              <a-col :lg="6" :md="12" :sm="24">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('otherJS.promotionOrderType')" data-step="2" :data-title="$t('otherJS.promotionOrderType')"
                  :data-intro="$t('otherJS.promotionOrderType')">
                  <a-select :placeholder="$t('purchasingManagement.selectPromotionOrderType')" :dropdownMatchSelectWidth="false" v-decorator="['custom11',validatorRules.custom11]">
                    <a-select-option :value="1">{{ $t('otherJS.manufacturerDirectHair') }}</a-select-option>
                    <a-select-option :value="2">{{ $t('manuManagement.purchaseOrder') }}</a-select-option>
                    <a-select-option :value="3">{{ $t('manuManagement.salesOrder') }}</a-select-option>
                    <a-select-option :value="4">{{ $t('setailManagement.retail') }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              
              <a-col :lg="6" :md="12" :sm="24">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('otherJS.applicableCustomers')" data-step="1" :data-title="$t('manuManagement.customer')"
                  :data-intro="$t('popup.customerMustUser')">
                  <a-select :placeholder="$t('manuManagement.selectCustomer')" v-decorator="[ 'holdSupplier', validatorRules.holdSupplier ]" v-model="queryParam.holdSupplier"
                    :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                    <a-select-option :value="1">{{$t('popup.allCustomers')}}</a-select-option>
                    <a-select-option :value="2" v-if="form.getFieldValue('custom11') == 3">{{$t('popup.someCustomers')}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              
            
              <a-col v-if="form.getFieldValue('custom11') == 3 && form.getFieldValue('holdSupplier') == 2" :lg="6" :md="12" :sm="24">
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('basicInformation.customer')" data-step="1" :data-title="$t('basicInformation.customer')"
                    :data-intro="$t('popup.customerMustUser')">
                    <a-select mode="multiple" :placeholder="$t('manuManagement.selectCustomer')" v-decorator="[ 'customerIds', validatorRules.customerIds ]"
                      :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                  <div slot="dropdownRender" slot-scope="menu">
                        <v-nodes :vnodes="menu" />
                        <a-divider style="margin: 4px 0;" />
                        <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;"
                            @mousedown="e => e.preventDefault()" @click="addCustomer"><a-icon type="plus" /> {{$t('popup.newCustomers')}}</div>
                      </div>
                    <a-select-opt-group>
                      <span slot="label">{{$t('inPrint.self')}}</span>
                      <a-select-option v-for="(item, index) in selfCustomer" :key="index" :value="item.id">
                      {{ item.supplier }}
                    </a-select-option>
                    </a-select-opt-group>
                    <a-select-opt-group :label="$t('inPrint.other')">
                      <a-select-option v-for="(item, index) in othoerCustomer" :key="index" :value="item.id">
                      {{ item.supplier }}
                    </a-select-option>
                    </a-select-opt-group>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :lg="6" :md="12" :sm="24">
                <a-form-item :label="$t('otherJS.promotionDate')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-range-picker
                      style="width:100%"
                      v-decorator="[ 'createTimeRange', validatorRules.createTimeRange ]"
                      format="YYYY-MM-DD"
                      :placeholder="[$t('setailManagement.startTime'),$t('setailManagement.endTime')]"
                      @change="onDateCXTJChange"
                      @ok="onDateOk"
                    />
                </a-form-item>
              </a-col>
          
              <a-col :lg="6" :md="12" :sm="24">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
                  <j-date v-decorator="['operTime', validatorRules.operTime]" :show-time="true"/>
                </a-form-item>
              </a-col>
              <a-col :lg="6" :md="12" :sm="24">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')" data-step="2" :data-title="$t('setailManagement.documentNo')"
                  :ata-intro="$t('popup.theDocumentOpened')">
                  <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="[ 'promotionNo' ]" :readOnly="true"/>
                </a-form-item>
              </a-col> 
          <!-- 操作员 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')"
              data-step="3" :data-title="$t('defaultTranslate.operator')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator.trim="['userName']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator.trim="['creator']" />
            </a-form-item>
          </a-col>
            </a-row>
            <j-editable-table id="billModal"
                  :ref="refKeys[0]"
                  :loading="materialTable.loading"
                  :columns="materialTable.columns"
                  :dataSource="materialTable.dataSource"
                  :minWidth="minWidth"
                  :maxHeight="300"
                  :rowNumber="false"
                  :rowSelection="true"
                  :actionButton="true"
                  :dragSort="true"
                  @valueChange="onValueChange"
                  @added="onAdded"
                  @deleted="onDeleted">
                  <!-- <template #buttonAfter>
                    <a-row :gutter="24" style="float:left;" data-step="4" :data-title="$t('popup.priceFormula')" :data-intro="$t('popup.priceFormula')">
                      <a-col :md="6" :sm="24">
                        <a-button @click="priceFormula">{{$t('popup.priceFormula')}}</a-button>
                      </a-col>
                    </a-row>
                  </template> -->
                </j-editable-table>
            <a-row class="form-row" :gutter="24">
                  <a-col :lg="24" :md="24" :sm="24">
                    <a-form-item :labelCol="labelCol" :wrapperCol="{xs: { span: 24 },sm: { span: 24 }}" label="">
                      <a-textarea :rows="1" :placeholder="$t('reportQuery.pleaseEnterComments')" v-decorator="[ 'remark' ]" style="margin-top:8px;"/>
                    </a-form-item>
                  </a-col>
                </a-row>
      </a-form>
    </a-spin>
    <many-account-modal ref="manyAccountModalForm" @ok="manyAccountModalFormOk"></many-account-modal>
    <customer-modal ref="customerModalForm" @ok="customerModalFormOk"></customer-modal>
    <account-modal ref="accountModalForm" @ok="accountModalFormOk"></account-modal>
    <!-- <price-formula-modal ref="priceFormulaModalForm" :visible="priceVisible" @priceList="priceList" @visibleType="visibleType" @ok="priceFormulaModalFormOk"></price-formula-modal> -->
    <!-- <history-bill-list ref="historyBillListModalForm"></history-bill-list> -->
  </j-modal>
</template>
<script>
  import pick from 'lodash.pick'
  import moment from 'moment';
  import { postAction,getAction } from '@/api/manage'
  import ManyAccountModal from '../dialog/ManyAccountModal'
  // import PriceFormulaModal from './PriceFormulaModal'
  import CustomerModal from '../../system/modules/CustomerModal'
  import AccountModal from '../../system/modules/AccountModal'
  import HistoryBillList from '../dialog/HistoryBillList'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { BillModalMixin } from '../mixins/BillModalMixin'
  import { getMpListShort,handleIntroJs } from "@/utils/util"
  import { BillListMixin } from '../mixins/BillListMixin'
  import JSelectMultiple from '@/components/jeecg/JSelectMultiple'
  import JUpload from '@/components/jeecg/JUpload'
  import JDate from '@/components/jeecg/JDate'
  import Vue from 'vue'
  export default {
    name: "QuantityMoneyModal",
    mixins: [JEditableTableMixin, BillModalMixin, BillListMixin],
    components: {
      ManyAccountModal,
      CustomerModal,
      AccountModal,
      // PriceFormulaModal,
      HistoryBillList,
      JUpload,
      JDate,
      JSelectMultiple,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
    },
    
    provide(){
      return {
        getConfig: ()=>{
          return {enableBatchNumber:'1'}
        }
      }
    },
    data () {
      return {
        title:this.$t('setailManagement.operation'),
        width: '1600px',
        queryParam: {
          holdSupplier: 1,
          holdDepot: 1,
        },
        UserHandler: [],
        moreStatus: false,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        priceVisible: false,
        visible: false,
        operTimeStr: '',
        prefixNo: 'MJ',
        fileList:[],
        model: {},
        anotherCustomerList:[],
        selfCustomer:[],
        othoerCustomer:[],
        supplierList:[],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        refKeys: ['materialDataTable'],
        activeKey: 'materialDataTable',
        materialTable: {
          loading: false,
          dataSource: [],
          columns: [
            // { title: '仓库名称', key: 'depotId', width: '7%', type: FormTypes.hidden },
            { title: this.$t('otherJS.goodsId'), key: 'materialId', width: '17%', type: FormTypes.hidden },
            { title: this.$t('reportQuery.barcode'), key: 'barCode', width: '17%', type: FormTypes.popupJsh, kind: 'material', multi: true,
              // validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') }]
            },
            { title: this.$t('otherJS.goodsId'), key: 'meId', width: '16%', type: FormTypes.hidden },
            { title: this.$t('reportQuery.name'), key: 'name', width: '16%', type: FormTypes.normal },
            // { title: '规格', key: 'standard', width: '15%', type: FormTypes.normal },
            { title: this.$t('reportQuery.category'), key: 'categoryName', width: '6%', type: FormTypes.input,readonly:true  },
            { title: this.$t('reportQuery.model'), key: 'model', width: '15%', type: FormTypes.normal },
            { title: this.$t('otherJS.fullPurchaseAmount'), key: 'fullAmout', width: '15%', type: FormTypes.input },
            { title: this.$t('otherJS.deductionAmount'), key: 'creditAmount', width: '15%', type: FormTypes.input },
            { title: this.$t('reportQuery.color'), key: 'color', width: '5%', type: FormTypes.normal },
                        // { title: '扩展信息', key: 'materialOther', width: '5%', type: FormTypes.normal },
            // { title: '库存', key: 'stock', width: '5%', type: FormTypes.normal },
            // { title: '单位', key: 'unit', width: '4%', type: FormTypes.normal },
            // { title: '多属性', key: 'sku', width: '4%', type: FormTypes.normal },
            // { title: '数量', key: 'operNumber', width: '5%', type: FormTypes.inputNumber, statistics: true,
            //   validateRules: [{ required: true, message: '${title}不能为空' }]
            // },
            // { title: '零售价', key: 'retailPrice', width: '5%', type: FormTypes.inputNumber},
            // { title: '折扣', key: 'discount', width: '5%', type: FormTypes.inputNumber},
            // { title: '特价', key: 'specialPrice', width: '5%', type: FormTypes.inputNumber},
            // { title: '每单限量', key: 'limitPerOrder', width: '5%', type: FormTypes.inputNumber},
            // { title: '累计限量', key: 'cumulativeLimit', width: '5%', type: FormTypes.inputNumber},
            // { title: '已促销数量', key: 'unitPrice', width: '6%', type: FormTypes.inputNumber},
            // { title: '零售价', key: 'unitPrice', width: '5%', type: FormTypes.inputNumber},
            // { title: '金额', key: 'allPrice', width: '5%', type: FormTypes.inputNumber, statistics: true },
            // { title: '税率', key: 'taxRate', width: '4%', type: FormTypes.inputNumber,placeholder: '%'},
            // { title: '税额', key: 'taxMoney', width: '5%', type: FormTypes.inputNumber, readonly: true, statistics: true },
            // { title: '价税合计', key: 'taxLastMoney', width: '6%', type: FormTypes.inputNumber, statistics: true },
            // { title: '备注', key: 'remark', width: '5%', type: FormTypes.input }
          ]
        },
        customerTable: {
          loading: false,
          dataSource: [],
          columns: [
            { title: this.$t('popup.customerName'), key: 'name1', width: '8%', type: FormTypes.popupJsh, kind: 'material', multi: true,
              validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') }]
            },
          ]
        },
        holdDepotTable: {
          loading: false,
          dataSource: [],
          columns: [
            { title: this.$t('setailManagement.warehouseName'), key: 'name2', width: '8%', type: FormTypes.popupJsh, kind: 'material', multi: true,
              validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') }]
            },
          ]
        },
        accountIdList: [],
        confirmLoading: false,
        validatorRules:{
          createTimeRange:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectDate')+'!' }
            ]
          },
          promotionName:{
            rules: [
              { required: true, message: this.$t('popup.pleaseEnterNamePromotion')+'!' }
            ]
          },
          operTime:{
            rules: [
              { required: true, message: this.$t('popup.pleaseEnterDocumentDate')+'!' }
            ]
          },
          holdSupplier:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectCustomer')+'!' }
            ]
          },
          custom11:{
            rules: [
              { required: true, message: this.$t('purchasingManagement.selectPromotionOrderType')+'!' }
            ]
          },
          holdDepot:{
            rules: [
              { required: true, message: this.$t('setailManagement.pleaseWarehouse')+'!' }
            ]
          },
          customerIds:{
            rules: [
              { required: true, message: this.$t('manuManagement.selectCustomer')+'!' }
            ]
          },
        },
        url: {
          add: '/promotionHead/addPromotionHeadAndDetail',
          edit: '/promotionHead/updatePromotionHeadAndDetail',
          detailList: '/promotionHead/getDetailList'
        }
      }
    },
    created () {
    },
    methods: {
      moment,
      priceList(item) {
        item.forEach((item1,index) => {
          item1.name = this.materialTable.dataSource[index].name
          item1.stock = this.materialTable.dataSource[index].stock
          item1.model = this.materialTable.dataSource[index].model
          item1.standard = this.materialTable.dataSource[index].standard
          item1.unit = this.materialTable.dataSource[index].unit
          item1.unitPrice = this.materialTable.dataSource[index].unitPrice
          item.materialId = this.materialTable.dataSource[index].id
        })
        this.materialTable.dataSource = item
      },
      visibleType(type){
        this.priceVisible = type
      },
      priceFormula() {
        this.priceVisible = true
        this.$refs.priceFormulaModalForm.editAfter(this.materialTable.dataSource)
      },
      // 获取经手人
      getHandler() {
        let param = {
          'currentPage': '1',
          'pageSize': '10'
        }
        getAction("/person/list", param).then(res=>{
          if(res.code == '200') {
            this.UserHandler = res.data.rows
          }
        })
      },
      //调用完edit()方法之后会自动调用此方法
      editAfter() {
        this.arrList = []
        this.getHandler()
        this.billStatus = '0'
        this.changeColumnHide()
        if (this.action === 'add') {
          this.addInit(this.prefixNo)
          this.personList.value = ''
          this.fileList = []
          this.$nextTick(() => {
            handleIntroJs(this.prefixNo, 1)
          })
        } else {
          this.model.operTime = this.model.createTimeStr
          this.supplierList = this.model.supplierList
          if(this.model.accountId == null) {
            this.model.accountId = 0
            this.manyAccountBtnStatus = true
            this.accountIdList = this.model.accountIdList
            this.accountMoneyList = this.model.accountMoneyList
          } else {
            this.manyAccountBtnStatus = false
          }
          this.personList.value = this.model.salesMan
          this.model.userName = this.model.creatorName
          this.model.customerIds = this.model.supplierIds
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model,'holdSupplier', 'materialId', 'operTime', 'promotionNo', 'remark', 'person', 'startTime','endTime','custom11','creator','userName',
              'discount','discountMoney','discountLastMoney','accountId','changeAmount','salesMan','createTimeRange','holdDepot','promotionName'))
            this.form.setFieldsValue({'createTimeRange': [moment(this.model.startTimeStr ),moment(this.model.endTimeStr) ] })
            setTimeout(()=>{
              this.form.setFieldsValue({'customerIds': this.model.customerIds })
            },200);
          });
          // 加载子表数据
          let params = {
            headerId: this.model.id,
            mpList: getMpListShort(Vue.ls.get('materialPropertyList'))  //扩展属性
          }
          let url = this.readOnly ? this.url.detailList : this.url.detailList;
          this.requestSubTableData(url, params, this.materialTable);
          let arr = []
          this.materialTable.dataSource.forEach(item => {
            arr.push(item.materialId)
          });
          this.materialIds = arr.toString()
          this.changeMaterialIds()
        }
        //复制新增单据-初始化单号和日期
        if(this.action === 'copyAdd') {
          this.model.id = ''
          this.model.tenantId = ''
          this.copyAddInit(this.prefixNo)
        }
        this.getAnotherCustomerData()
      },
      //提交单据时整理成formData
      classifyIntoFormData(allValues) {
        let totalPrice = 0
        let billMain = Object.assign(this.model, allValues.formValue)
        let detailArr = allValues.tablesValue[0].values
        billMain.type = '其它'
        billMain.subType = '销售订单'
        billMain.defaultNumber = billMain.promotionNo
        if(billMain.customerIds && billMain.customerIds.length){
          billMain.supplierList = billMain.customerIds.map(v=>{
            let item ={}
            let index = this.supplierList.findIndex(val=>val.supplierId === v)
            if(index > -1){
              item = {
                supplierId:v,
                id:this.supplierList[index].id,
                headerId:this.supplierList[index].headerId
              }
            }else{
              item = {
                supplierId:v,
              }
            }
            return item
          })
          billMain.holdSupplier = 2
        }
        if(this.model.id){
          billMain.id = this.model.id
        }
        billMain.status = this.billStatus
        let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
        return {
          info: JSON.stringify(billMain),
          attachment: fileList,
          rows: JSON.stringify(detailArr),
        }
      },
      handleHistoryBillList() {
        let holdSupplier = this.form.getFieldValue('holdSupplier')
        this.$refs.historyBillListModalForm.show(this.$t('manuManagement.other'),this.$t('manuManagement.salesOrder'),this.$t('manuManagement.customer'), holdSupplier);
        this.$refs.historyBillListModalForm.disableSubmit = false;
      },
      getAnotherCustomerData() {
        postAction('/supplier/findBySelectNotTenant_cus').then(res => {
          this.anotherCustomerList = res
            let creator = this.getLocalStorage('pro__Login_Userinfo').tenantId
            this.selfCustomer = this.anotherCustomerList.filter(v=>v.tenantId === creator)
            this.othoerCustomer = this.anotherCustomerList.filter(v=>v.tenantId !== creator)
        })
      },
    }
  }
</script>
<style scoped>

</style>